package com.tc.groovy

import com.tc.groovy.entity.Chinese
import com.tc.groovy.entity.User
import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer


/**
 * Created by cai.tian on 2018/1/17.
 */
class Configurator {
    void run(File file) {
        run(file.text);
    }
    //调用groovy脚本
    void run(String dslText) {
        Binding binding = new Binding();
        binding.setProperty("hostname", "tc");
        def configuration = new CompilerConfiguration()
        configuration.addCompilationCustomizers(importCustomizer())
        Script dslScript = new GroovyShell(binding, configuration).parse(dslText)
        //处理脚本类
        dslScript.metaClass.mixin(ConfigDelegate)
        dslScript.metaClass.getDeclaredOrigin = { dslScript }
        //执行脚本
        dslScript.run()
    }


    protected ImportCustomizer importCustomizer() {
        def customizer = new ImportCustomizer()
        customizer.addImports(User.class.name)
        customizer.addImports(Chinese.class.name)
        customizer
    }
}
